<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->

      <el-row :gutter="20">
        <el-col :span="7">
          <el-input @clear="getUserList" clearable placeholder="请输入内容" v-model="queryInfo.query">
            <el-button slot="append" icon="el-icon-search" @click="getUserList()"> </el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽 slot获取数据 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"> </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-tooltip :enterable="false" class="item" effect="dark" content="修改" placement="top">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditForm(scope.row.id)"></el-button>
            </el-tooltip>

            <el-tooltip :enterable="false" class="item" effect="dark" content="删除" placement="top">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleUserById(scope.row.id)"></el-button>
            </el-tooltip>

            <el-tooltip :enterable="false" class="item" effect="dark" content="权限分配" placement="top">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
      <!-- 添加用户的对话框  -->
      <!-- 监听close事件触发重置添加框 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose()">
        <!-- 内容主体区域 -->
        <el-form :model="addUser" :rules="addUserRules" ref="addUserRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUser.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUser.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUser.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addUser.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域s -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUsers()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 修改用户信息对话框 -->
      <el-dialog title="修改信息" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose()">
        <el-form :model="edifForm" :rules="edifFormRules" ref="edifFormRef" label-width="70px">
          <el-form-item label="用户名">
            <el-input v-model="edifForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="edifForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="edifForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser()">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色对话框 -->
      <el-dialog @close="setRoleClose()" title="分配角色" :visible.sync="setRoleDialogVisible" width="50%">
        <div>
          <p>当前用户:{{ userInfo.username }}</p>
          <p>当前角色:{{ userInfo.role_name }}</p>
          <p>
            分配角色：
            <el-select v-model="selectRoleId" placeholder="请选择">
              <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id"> </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveRoleInfo()">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义邮箱验证规则
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/

      if (regEmail.test(value)) return cb()

      cb(new Error('请输入正确的邮箱号'))
    }
    // 自定义手机号验证规则
    var checkPhone = (rule, value, cb) => {
      const regPhone = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/

      if (regPhone.test(value)) return cb()

      cb(new Error('请输入正确的手机号'))
    }
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      // 控制对话框是否显示
      addDialogVisible: false,
      // 添加用户的表单数据
      addUser: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 修改信息对象
      edifForm: {},
      // 添加表单的验证规则对象
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名长度在3到10个字符间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '密码长度在6到12个字符间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱号', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          // { pattern: /^[1][3,4,5,7,8][0-9]{9}$/, message: '手机号格式不正确', trigger: 'blur' }
          { validator: checkPhone, trigger: 'blur' }
        ]
      },
      // 修改对话框验证对象
      edifFormRules: {
        email: [
          { required: true, message: '请输入邮箱号', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          // { pattern: /^[1][3,4,5,7,8][0-9]{9}$/, message: '手机号格式不正确', trigger: 'blur' }
          { validator: checkPhone, trigger: 'blur' }
        ]
      },
      // 控制修改对话框
      editDialogVisible: false,
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      rolesList: [],
      // 已选中的角色ID值
      selectRoleId: []
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.userList = res.data.users
      this.total = res.data.total
      // console.log(res)
    },
    // 监听pagesize改变事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 监听状态改变
    async userStateChange(userinfo) {
      const { data: res } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error(`${res.meta.msg}`)
      }
      this.$message.success(`${res.meta.msg}`)
    },
    // 重置添加内容
    addDialogClose() {
      this.$refs.addUserRef.resetFields()
    },
    // 点击确定添加用户
    addUsers() {
      this.$refs.addUserRef.validate(async (valid) => {
        if (!valid) return
        // 可以添加请求
        const { data: res } = await this.$http.post('users', this.addUser)
        if (res.meta.status !== 201) {
          return this.$message.error(`${res.meta.msg}`)
        }
        this.$message.success(`${res.meta.msg}`)
        this.addDialogVisible = false
        this.getUserList()
      })
    },
    async showEditForm(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(`${res.meta.msg}`)
      }

      this.edifForm = res.data
      this.editDialogVisible = true
    },
    editDialogClose() {
      this.$refs.edifFormRef.resetFields()
    },
    // 修改用户信息
    editUser() {
      this.$refs.edifFormRef.validate(async (valid) => {
        if (!valid) return
        // 可以发送请求
        const { data: res } = await this.$http.put('users/' + this.edifForm.id, { email: this.edifForm.email, mobile: this.edifForm.mobile })
        if (res.meta.status !== 200) {
          return this.$message.error(`${res.meta.msg}`)
        }
        // console.log(res)
        if (res.data.email === this.edifForm.email && res.data.mobile === this.edifForm.mobile) {
          return this.$message('信息无修改')
        }
        this.editDialogVisible = false
        this.getUserList()
        this.$message.success(`${res.meta.msg}`)
      })
    },
    // 根据ID删除用户信息
    async deleUserById(id) {
      // 弹框显示是否删除
      const result = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      // 如果用户确认删除，返回值为confirm
      // 取消删除，返回值为cancel

      if (result !== 'confirm') {
        return this.$message('取消操作')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(`${res.meta.msg}`)
      }
      this.$message.success(`${res.meta.msg}`)
      if (this.users.length === 1) {
        // 判断当前展示的用户数据是否只有一条
        this.queryInfo.pagenum = this.queryInfo.pagenum === 1 ? 1 : this.queryInfo.pagenum - 1 // 若是，则继续判断页码是否已经在第一页，若否，则-1，若是则保持在该页
      }

      this.getUserList()
    },
    // 分配角色对话框
    async setRole(userInfo) {
      this.userInfo = userInfo
      // 获取所有角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error(`${res.meta.msg}`)
      }
      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    // 点击按钮保存
    async saveRoleInfo() {
      if (!this.selectRoleId) {
        return this.$message.error('角色未更新')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectRoleId })
      if (res.meta.status !== 200) {
        return this.$message.error(`${res.meta.msg}`)
      }
      this.$message.success(`${res.meta.msg}`)
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    // 监听对话框关闭
    setRoleClose() {
      this.selectRoleId = ''
      this.userInfo = []
    }
  }
}
</script>

<style lang="less" scoped></style>
